package com.oss.common;

import com.alibaba.fastjson2.JSON;
import lombok.Data;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * 返回值
 * @param <T> 泛型
 * @author chengqiang
 */
@Data
public class BaseResponse<T> implements Serializable {

    /**
     * 响应状态
     * 通用 :
     *      0:失败
     *      1:成功
     *      -1:无token(未登录)或token失效
     *      -2:用户名或密码错误
     */
    private int code;
    // 响应的返回数据
    private T data;
    // 额外的响应数据
    private T extraData ;
    // 响应信息
    private String message;


    /**
     * 构造函数
     * @param code 状态码
     * @param data 向前端传的数据
     * @param message 操作反馈信息：如登录成功、查询成功、查询失败、账号密码错误等提示信息。有利于后续纠错。
     */
    public BaseResponse(int code, T data, String message, T extraData) {
        this.code = code;
        this.data = data;
        this.message = message;
        this.setExtraData(extraData);
    }
    public BaseResponse(int code, String message) {
        this.code = code;
        this.message = message;
    }
    public BaseResponse() {
    }
    public static BaseResponse error(int code,String message) {
        return new BaseResponse(code,null,message,null);
    }
    public static BaseResponse error(String message) {
        return new BaseResponse(0,message);
    }
    public static <T> BaseResponse error(T data,String message) {
        return new BaseResponse(0,data,message,null);
    }
    public static <T>  BaseResponse success(T data) {
        return new BaseResponse(1,data,"request success",null);
    }
    public static BaseResponse success(String message) {
        return new BaseResponse(1,message);
    }
    public static <T>  BaseResponse success(T data,String message) {
        return new BaseResponse(1,data,message,null);
    }

    /**
     * 响应一个错误信息
     * @param response response
     * @param message 错误信息
     */
    public static void tokenError(HttpServletResponse response, String message){
        try (ServletOutputStream out = response.getOutputStream()){
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            out.write(JSON.toJSONString(BaseResponse.error(-1,message)).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 响应一个错误信息: 用户名或密码错误
     * @param response response
     * @param message 错误信息
     */
    public static void usernameOrPwdError(HttpServletResponse response, String message){
        try (ServletOutputStream out = response.getOutputStream()){
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            out.write(JSON.toJSONString(BaseResponse.error(-2,message)).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}